package com.mishow.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.adapter.StarDetailsCommnetAdapter;
import com.mishow.adapter.StarResultFragmentAdapter.OnCommnetInfoClick;
import com.mishow.bean.ChatDetail;
import com.mishow.bean.CommentChatDetail;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.refresh.PullPushRefreshLayout;
import com.mishow.request.core.Response;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.ChatDetailResponse;
import com.mishow.request.response.CommentChatDetailResponse;
import com.mishow.request.response.CommentChatDetailResponse.Result;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.TimeUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.AdjustLayout;
import com.mishow.widget.MyListView;
import com.mishow.widget.RoundCornerImageView;
import com.mishow.widget.nine.CustomImageView;
import com.mishow.widget.nine.Image;
import com.mishow.widget.nine.NineGridlayout;
import com.mishow.widget.nine.ScreenTools;
import com.mishow.widget.share.ShareDialog;
import com.mishow.widget.share.ShareView;
import com.mishow.widget.share.ShareUtil.ShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

/**
 * 作者：wei.miao <br/>
 * 描述：星秀详情
 */
public class StarDetailsActivity extends BaseActivity implements
		OnRefreshListener, PullPushRefreshLayout.OnLoadListener {

	private Button btn_back;
	private TextView title_tv;
	/** 分享 **/
	private ImageButton btn_right;

	/** 下拉刷新 **/
	private PullPushRefreshLayout refresh_layout;
	private int pageNo = 1;

	private int pageSize = 10;

	/** 列表总条数 **/
	private int total;
	/** 是否正在网络请求中默认为false **/
	private boolean isReflesh;
	/** 刷新操作 **/
	public static final int ACTION_REFRESH = 1;
	/** 加载更多操作 **/
	public static final int ACTION_LOAD_MORE = 2;

	/** 发布人头像 **/
	RoundCornerImageView img_round_icon;

	/** 昵称 **/
	TextView txt_star_nikename;
	/** 是否实名 **/
	ImageView image_is_name;
	/** 职业类型 **/
	AdjustLayout adjust_plane_layout;
	/** 关注点击 **/
	Button btn_comment_focus;
	/** 描述 **/
	TextView txt_star_desc;
	/** 位置 **/
	TextView text_star_location;
	/** 评论更新时间 **/
	TextView text_comment_update_time;

	/** 点赞点击 **/
	ImageView image_like;

	/** 评论头像 1 **/
	RoundCornerImageView image_head_one;
	/** 评论头像 2 **/
	RoundCornerImageView image_head_two;
	/** 评论头像 3 **/
	RoundCornerImageView image_head_three;
	/** 评论头像 4 **/
	RoundCornerImageView image_head_four;
	/** 评论头像 5 **/
	RoundCornerImageView image_head_five;
	/** 评论头像 6 **/
	RoundCornerImageView image_head_six;

	/** 点赞数量 **/
	TextView text_like_number;

	/** 分享转发点击 **/
	ImageView img_like_share;

	RelativeLayout relative_comment_content;
	/** 评论列表 **/
	MyListView listview_starshow_detail;

	/** 输入评论 **/
	EditText edit_comment;

	/** 评论点击 **/
	TextView text_content;

	/** 九宫格 **/
	NineGridlayout iv_ngrid_layout;
	/** 九宫格 **/
	View include_nine;
	/** 九宫格 **/
	CustomImageView iv_oneimage;

	/** 星秀ID **/
	private String mStarId;

	private SharedPreferencesUtil preferencesUtil;

	private ArrayList<CommentChatDetail> mCommentVOs;

	private StarDetailsCommnetAdapter mCommnetAdapter;

	private ArrayList<Image> mDatalist;

	private ChatDetail mDatail;

	public static void intoActivity(Context context, String starId) {

		Intent intent = new Intent(context, StarDetailsActivity.class);
		intent.putExtra(Constants.STAR_ID, starId);
		context.startActivity(intent);
	}

	@Override
	protected void initData() {

		if (getIntent() != null) {
			mStarId = getIntent().getStringExtra(Constants.STAR_ID);
		}
		preferencesUtil = new SharedPreferencesUtil(mContext);
		mDatalist = new ArrayList<Image>();
		mCommentVOs = new ArrayList<>();
		mCommnetAdapter = new StarDetailsCommnetAdapter(mContext, mCommentVOs);
	}

	@Override
	protected void initView(Bundle savedInstanceState) {

		setContentView(R.layout.activity_starshow_detail);
		title_tv = (TextView) findViewById(R.id.title_tv);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_right = (ImageButton) findViewById(R.id.btn_right);

		img_round_icon = (RoundCornerImageView) findViewById(R.id.img_round_icon);
		txt_star_nikename = (TextView) findViewById(R.id.txt_star_nikename);
		image_is_name = (ImageView) findViewById(R.id.image_is_name);
		adjust_plane_layout = (AdjustLayout) findViewById(R.id.adjust_plane_layout);

		txt_star_desc = (TextView) findViewById(R.id.txt_star_desc);
		text_star_location = (TextView) findViewById(R.id.text_star_location);
		text_comment_update_time = (TextView) findViewById(R.id.text_comment_update_time);

		image_head_one = (RoundCornerImageView) findViewById(R.id.image_head_one);
		image_head_two = (RoundCornerImageView) findViewById(R.id.image_head_two);
		image_head_three = (RoundCornerImageView) findViewById(R.id.image_head_three);
		image_head_four = (RoundCornerImageView) findViewById(R.id.image_head_four);
		image_head_five = (RoundCornerImageView) findViewById(R.id.image_head_five);
		image_head_six = (RoundCornerImageView) findViewById(R.id.image_head_six);

		text_like_number = (TextView) findViewById(R.id.text_like_number);

		listview_starshow_detail = (MyListView) findViewById(R.id.listview_starshow_detail);
		refresh_layout = (PullPushRefreshLayout) findViewById(R.id.refreshLayout_start);
		relative_comment_content = (RelativeLayout) findViewById(R.id.relative_comment_content);

		edit_comment = (EditText) findViewById(R.id.edit_comment);
		// 九宫格start
		include_nine = findViewById(R.id.include_nine);
		iv_oneimage = (CustomImageView) findViewById(R.id.iv_oneimage);
		iv_ngrid_layout = (NineGridlayout) findViewById(R.id.iv_ngrid_layout);
		// 九宫格end

		btn_comment_focus = (Button) findViewById(R.id.btn_comment_focus);
		image_like = (ImageView) findViewById(R.id.image_like);
		img_like_share = (ImageView) findViewById(R.id.img_like_share);
		text_content = (TextView) findViewById(R.id.text_content);
	}

	@Override
	protected void setAttribute() {
		title_tv.setText("动态详情");
		btn_back.setOnClickListener(onClickListener);
		btn_right.setOnClickListener(onClickListener);
		btn_right.setVisibility(View.VISIBLE);
		btn_right.setImageResource(R.drawable.icon_share);

		text_content.setOnClickListener(onClickListener);
		img_like_share.setOnClickListener(onClickListener);
		image_like.setOnClickListener(onClickListener);
		btn_comment_focus.setOnClickListener(onClickListener);

		listview_starshow_detail.setAdapter(mCommnetAdapter);
		refresh_layout.setOnRefreshListener(this);
		refresh_layout.setOnLoadListener(this);

		mCommnetAdapter.setOnCommentInfoClick(new OnCommnetInfoClick() {

			@Override
			public void setEditText(String commentRespondentCname) {

				edit_comment.requestFocus();
				edit_comment.setHint("回复" + commentRespondentCname);
				InputMethodManager imm = (InputMethodManager) mContext
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(edit_comment,
						InputMethodManager.SHOW_IMPLICIT);
			}

		});

		getStarDetailFromApi(mStarId);

		onRefresh();
	}

	/**
	 * 服务端获取星秀动态详情信息
	 * 
	 * @param statId
	 *            通告ID
	 */
	private void getStarDetailFromApi(String statId) {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("id", statId);
		params.put("currUserId", preferencesUtil.getUserId());

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,
				HttpUrlConstant.GET_CHAT_DETAILS);
		OnResponseListener<ChatDetailResponse> listener = new OnResponseListener<ChatDetailResponse>(
				this) {

			@Override
			public void onSuccess(ChatDetailResponse response) {

				ChatDetail result = response.getBody().getResult();
				if (result != null) {

					setDisplayData(result);
				}
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {
				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<ChatDetailResponse>(
				Request.Method.POST, postUrl, ChatDetailResponse.class,
				listener, listener).setParams(lastParams));
	}

	/**
	 * 设置显示数据
	 */
	private void setDisplayData(ChatDetail detail) {

		mDatail = detail;
		// 发布人头像
		// PicassoImageLoaderUtil.loadImage(mContext, "",holder.img_round_icon);
		txt_star_nikename.setText(detail.getUserCname());
		if (detail.getChatCreatetime() != null && !detail.getChatCreatetime().equals("")) {
			String str_time = TimeUtil.update_time(detail.getChatCreatetime());
			text_comment_update_time.setText(str_time);
		}
		// 是否实名
		image_is_name.setVisibility(detail.getRealName() == 1 ? View.VISIBLE: View.GONE);

		if (detail.getUserProfession() != null
				&& !detail.getUserProfession().equals("")) {
			adjust_plane_layout.setVisibility(View.VISIBLE);
			if (detail.getUserProfession().contains(",")) {
				String[] tempPro = detail.getUserProfession().split(",");
				for (int i = 0; i < tempPro.length; i++) {

					View view_plane = LayoutInflater.from(mContext).inflate(
							R.layout.item_comment_pro, null);
					CheckBox textView = (CheckBox) view_plane
							.findViewById(R.id.hot_search_text);
					textView.setText(tempPro[i]);
					textView.setSingleLine(true);
					textView.setEllipsize(TruncateAt.MIDDLE);
					adjust_plane_layout.addView(view_plane);
				}
			} else {

				View view_plane = LayoutInflater.from(mContext).inflate(
						R.layout.item_hot_search, null);
				CheckBox textView = (CheckBox) view_plane
						.findViewById(R.id.hot_search_text);
				textView.setText(detail.getUserProfession());
				textView.setSingleLine(true);
				textView.setEllipsize(TruncateAt.MIDDLE);
				textView.setBackgroundResource(R.drawable.shape_selectitem_press);
				adjust_plane_layout.addView(view_plane);
			}
		} else {

			adjust_plane_layout.setVisibility(View.GONE);
		}

		txt_star_desc.setText(detail.getChatText());

		text_star_location.setSingleLine(true);
		text_star_location.setEllipsize(TruncateAt.END);
		text_star_location.setText(detail.getChatPosition());
		text_like_number.setText(detail.getLikedNum() + "");
		if (detail.getImageList() != null && detail.getImageList().size() > 0) {

			setImage(detail.getImageList());
			if (mDatalist.isEmpty()) {
				iv_oneimage.setVisibility(View.GONE);
				include_nine.setVisibility(View.GONE);
			} else {
				if (mDatalist != null && mDatalist.size() > 0) {
					if (mDatalist.size() == 1) {
						include_nine.setVisibility(View.GONE);
						iv_oneimage.setVisibility(View.VISIBLE);
						handlerOneImage(iv_oneimage, mDatalist.get(0));
					} else {
						include_nine.setVisibility(View.VISIBLE);
						iv_oneimage.setVisibility(View.GONE);
						iv_ngrid_layout.setImagesData(mDatalist);
					}
				}
			}
		}

		/*
		 * String likedHead = mRedsBeans.get(position).getLikedHead(); if
		 * (likedHead != null && !likedHead.equals("")) {
		 * 
		 * }
		 */

	}

	private void setImage(ArrayList<String> images) {
		mDatalist = new ArrayList<>();
		for (int i = 0; i < images.size(); i++) {
			// 等比缩小 50%：压缩图片质量30
			Image image = new Image(images.get(i)
					+ "?imageMogr2/thumbnail/!50p/quality/20", 117, 117);
			mDatalist.add(image);

		}
	}

	private void handlerOneImage(CustomImageView oneimage, Image image) {

		int totalWidth;
		int imageWidth;
		int imageHeight;
		ScreenTools screentools = ScreenTools.instance(mContext);
		totalWidth = screentools.getScreenWidth() - screentools.dip2px(80);
		imageWidth = screentools.dip2px(image.getWidth());
		imageHeight = screentools.dip2px(image.getHeight());
		if (image.getWidth() <= image.getHeight()) {
			if (imageHeight > totalWidth) {
				imageHeight = totalWidth;
				imageWidth = (imageHeight * image.getWidth())
						/ image.getHeight();
			}
		} else {
			if (imageWidth > totalWidth) {
				imageWidth = totalWidth;
				imageHeight = (imageWidth * image.getHeight())
						/ image.getWidth();
			}
		}
		ViewGroup.LayoutParams layoutparams = oneimage.getLayoutParams();
		layoutparams.height = imageHeight;
		layoutparams.width = imageWidth;
		oneimage.setLayoutParams(layoutparams);
		oneimage.setClickable(true);
		oneimage.setScaleType(android.widget.ImageView.ScaleType.CENTER_INSIDE);
		oneimage.setImageUrl(image.getUrl());
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.btn_right: // 分享
				share();
				break;
			case R.id.btn_comment_focus:
				ToastUtil.show(mContext, "关注");
				break;
			case R.id.img_like_share:
				ToastUtil.show(mContext, "转发");
				break;
			case R.id.image_like:// 点赞
				doSaveLiked(mStarId);
				break;
			case R.id.text_content:
				if (edit_comment.getText().toString().trim().length() < 1) {

					ToastUtil.show(mContext, "请输入评论信息");
				} else {
					String comment = edit_comment.getText().toString().trim();
					// 判断当前登录userId是否用发布动态的userId相同
					// 如果相同表示是主题评论.否则为回复
					int type;
					if (preferencesUtil.getUserId().equals(mDatail.getUserId())) {
						type = 1;
					} else {
						type = 0;
					}
					doSaveComment(comment, mDatail.getUserId() + "",
							mDatail.getId() + "", "", type + "");
				}
				break;
			default:
				break;
			}

		}
	};

	private ShareDialog shareDialog;// 分享对话框

	/**
	 * 显示分享对话框
	 */
	private void share() {
		if (shareDialog == null) {
			shareDialog = new ShareDialog(this, ShareView.TYPE_SHARE_APP);
			shareDialog.setShareContent("title", "content", "http://www.baidu.com", "http://pic74.nipic.com/file/20150806/20968868_172407221000_2.jpg");
			shareDialog.setShareListener(new ShareListener() {
				
				@Override
				public void shareCallBack(SHARE_MEDIA platform, int result, String message) {
					
					ToastUtil.show(mContext, message);
				}
			});
		}
		shareDialog.show();
	}

	/**
	 * 点赞
	 */
	private void doSaveLiked(String chatId) {

		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("chatId", chatId);
		params.put("userId", preferencesUtil.getUserId());

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,
				HttpUrlConstant.SAVE_LIKED);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(
				mContext) {

			@Override
			public void onSuccess(Response response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				// 刷新数据
				getStarDetailFromApi(mStarId);
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(Request.Method.POST,
				postUrl, Response.class, listener, listener)
				.setParams(lastParams));

	}

	/**
	 * 请示服务端添加评论
	 * 
	 * @param comment
	 *            评论内容
	 * @param commentReviewersId
	 *            评论者ID
	 * @param commentChatId
	 *            评论内容ID
	 * @param commentRespondentId
	 *            被回复者ID
	 * @param commentType
	 *            评论类型(0-主题评论,1-回复)
	 * 
	 */
	private void doSaveComment(String comment, String commentReviewersId,
			String commentChatId, String commentRespondentId, String commentType) {

		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("commentText", comment);
		params.put("commentReviewersId", commentReviewersId);
		params.put("commentChatId", commentChatId);
		params.put("commentRespondentId", commentRespondentId);
		params.put("commentType", commentType);

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,
				HttpUrlConstant.SAVE_COMMENT);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(
				mContext) {

			@Override
			public void onSuccess(Response response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				// 刷新数据
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(Request.Method.POST,
				postUrl, Response.class, listener, listener)
				.setParams(lastParams));

	}

	/**
	 * 服务端获取星秀详情评论分布信息
	 * 
	 * @param statId
	 *            通告ID
	 */
	private void getCommentDetailFromApi(String statId, final int action) {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		if (isReflesh) {
			return;
		}
		isReflesh = true;
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("chatId", statId);// 星秀id
		params.put("pageNo", pageNo + "");// 第几页
		params.put("pageSize", pageSize + "");// 每页10条数据

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,
				HttpUrlConstant.GET_COMMNET_DETAILPAGE);
		OnResponseListener<CommentChatDetailResponse> listener = new OnResponseListener<CommentChatDetailResponse>(
				this) {

			@Override
			public void onSuccess(CommentChatDetailResponse response) {

				Result result = response.getBody().getResult();
				ArrayList<CommentChatDetail> dataList = result.getDataList();

				if (dataList != null && dataList.size() > 0) {
					total = response.getBody().getResult().getTotal();
					if (action == ACTION_REFRESH) {
						handlerRefresh(dataList);
					} else if (action == ACTION_LOAD_MORE) {
						handleLoadMore(dataList);
					}
				}
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
				if (action == ACTION_LOAD_MORE) {
					pageNo--;
				}
			}

			@Override
			public void onCompleted() {
				isReflesh = false;
				dismissProgress();
				loadCompleted();
			}
		};
		executeRequest(new FastJsonRequest<CommentChatDetailResponse>(
				Request.Method.POST, postUrl, CommentChatDetailResponse.class,
				listener, listener).setParams(lastParams));
	}

	@Override
	public void onLoad() {
		if (total > mCommentVOs.size()) {
			pageNo++;
			getCommentDetailFromApi(mStarId, ACTION_LOAD_MORE);
		} else {
			loadCompleted();
		}
	}

	@Override
	public void onRefresh() {
		pageNo = 1;
		getCommentDetailFromApi(mStarId, ACTION_REFRESH);
	}

	/**
	 * 加载完成
	 */
	private void loadCompleted() {

		refresh_layout.setRefreshing(false);
		refresh_layout.setLoading(false);
		// 获取到全部数据后，则隐藏加载更多
		if (total > mCommentVOs.size()) {
			refresh_layout.setCanLoadMore(true);
		} else {
			refresh_layout.setCanLoadMore(false);
		}
	}

	/**
	 * 刷新后的数据
	 * 
	 * @param results
	 */
	private void handlerRefresh(ArrayList<CommentChatDetail> results) {
		if (results == null || results.isEmpty()) {
			mCommentVOs.clear();
			mCommnetAdapter.notifyDataSetChanged();
			relative_comment_content.setVisibility(View.GONE);
		} else {
			relative_comment_content.setVisibility(View.VISIBLE);
			mCommentVOs.clear();
			mCommentVOs.addAll(results);
			mCommnetAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 加载更多数据
	 * 
	 * @param results
	 */
	private void handleLoadMore(ArrayList<CommentChatDetail> results) {
		if (results != null && !results.isEmpty()) {
			mCommentVOs.addAll(results);
			mCommnetAdapter.notifyDataSetChanged();
		}
	}

}
